package com.bm.server.serves;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

@Component //IOC创建对象
@Scope(scopeName = "prototype")//设置IOC创建对象的方式 为多例
@ServerEndpoint("/server/{uid}") //设置服务端的连接地址
public class WebSocketMore {
    //记录当前在线的所有订单号 key：订单号 value:会话对象
    public static ConcurrentHashMap<String,Session> map=new ConcurrentHashMap<>();

    private String uid;//
    //创建连接
    @OnOpen
    public void open(Session session, @PathParam("uid") String uid){
        //1.验证订单号是否存在
        if(map.containsKey(uid)){
            //订单号重复，返回消息
            try {
                session.getBasicRemote().sendText("请勿重新进入！");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else {
            //添加在线监听的订单号
            map.put(uid,session);
            this.uid=uid;
        }
    }
    //接收消息
    @OnMessage
    public void receive(String msg){
        System.err.println("服务器接收消息："+uid+"--->"+msg);
    }
    //出现错误
    @OnError
    public void error(Session session, Throwable throwable){
        System.err.println("错误："+throwable.getMessage());
    }
    //断开连接
    @OnClose
    public void close(){
        //退出监控
        map.remove(uid);
    }
    /**
     * 转发消息到指定订单号页面*/
    public static void sendSingleMsg(String uid,String msg){
        try {
            if(map.containsKey(uid)) {
                map.get(uid).getBasicRemote().sendText(msg);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**群发消息*/
    //群发消息
    public static void sendMoreMsg(String msg){
        //1，循环遍历在线用户
        map.keySet().forEach(s->{
            try {
                //发送消息
                map.get(s).getBasicRemote().sendText(msg);
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
    }
}
